﻿using System;
using System.Data;
using Pantry.Business;
using Pantry.Commons;
using System.Globalization;
using SiteUtils;

namespace Pantry.Web.Users
{
    public partial class ViewListProgram : System.Web.UI.Page
    {
        private DataView dataView;
        private static bool isSort = true;

        protected void Page_Load(object sender, EventArgs e)
        {
            Paging();
            if (!IsPostBack)
            {
                CheckBoxIncludeActivate.Checked = true;
            }
        }

        private void Paging()
        {
            var programBus = new ProgramBus();
            var listProgrammes = programBus.RetrieveAllData();
            dataView = listProgrammes.DefaultView;
            FillterIsAtive(CheckBoxIncludeActivate.Checked);
            CollectionPager.PageSize = 10;
            CollectionPager.BindToControl = RepeaterProgram;
            CollectionPager.DataSource = dataView;
            RepeaterProgram.DataSource = CollectionPager.DataSourcePaged;
            RepeaterProgram.DataBind();
        }

        protected void Sort(string field)
        {
            try
            {
                if(isSort)
                {
                    dataView.Sort = string.Format(CultureInfo.CurrentCulture,"{0} DESC", field);
                    isSort = false;
                }
                else
                {
                    dataView.Sort = string.Format(CultureInfo.CurrentCulture,"{0} ASC", field);
                    isSort = true;
                }
            }
            catch (Exception exception)
            {
                ExceptionHandler.WriteErrorLog(exception);
                throw;
            }
        }

        protected void ButtonSortByNameClick(object sender, EventArgs e)
        {
            Sort("ProgramName");
        }
        protected void ButtonSortByDescriptionClick(object sender, EventArgs e)
        {
            Sort("Description");
        }
        protected void ButtonSortByContactClick(object sender, EventArgs e)
        {
            Sort("ContactId");
        }
        protected void ButtonSortByStatusClick(object sender, EventArgs e)
        {
            Sort("IsActive");
        }

        protected void CheckBoxIncludeActivateChanged(object sender, EventArgs e)
        {
            FillterIsAtive(CheckBoxIncludeActivate.Checked);
        }

        private void FillterIsAtive(bool inActived)
        {
            dataView.RowFilter = inActived ? null : "IsActive = 'true'";
        }
    }
}
